package com.whc.config;

import com.whc.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author 韦红材
 * @ClassName WebSecurityConfig
 * @data 2024/12/20 21:21
 * @Version V1.0
 **/
@EnableGlobalMethodSecurity(prePostEnabled = true)  //开启方法的权限管理
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    //Spring Security的默认密码的编码方式BCryptPasswordEncoder
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    //这个bean主要是存放账号信息，辅助后期的权限认证
    @Bean
    public UserDetailsService userDetailsService(){
        DBUserDetailsManager dbUserDetailsManager = new DBUserDetailsManager();
        return dbUserDetailsManager;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 禁用 Spring Security 默认的登录页面
            .formLogin().disable()

            // 禁用 CSRF 防护
            .csrf().disable()

            // 配置需要认证的请求(这里不配置了，因为加了访问每个接口的权限)
            .authorizeRequests()
            .antMatchers("/ws/**","/common/upload").permitAll()

            // 配置跨域请求（如果需要）
            .and()
            .cors();


        // 将自定义的拦截器放入security的拦截器链中，并且指定其位置
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

}
